package com.prime.tutorial.moviestore.dao;

import com.prime.tutorial.moviestore.domain.Device;
import com.prime.tutorial.moviestore.domain.Location;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.List;


@Repository
//public class UserDAOWithJPA extends JpaDaoSupport implements UserDAO{
public class LocationDAOWithJPA extends GenericDAOWithJPA<Location, Long> implements LocationDAO {

    public List<Location> findByDevice(Device device) {
        Query query = entityManager.createQuery("Select distinct m from Location m, Device d where d.device = ?1");
        query.setParameter(1, device.getId());
        return query.getResultList();
    }

    public List<Location> findByAllDevices() {
        Query query = entityManager.createQuery("Select distinct l from Location l, Device d where d.location = l.id");
        return query.getResultList();
    }

    public List<Location> findByAllDevicesWithFreePorts() {
        Query query = entityManager.createQuery("Select distinct l from Location l, Device d,DevicePort dp,Port p where d.location = l.id and dp.device = d.id and dp.port = p.id and p.connected = ?1");
        query.setParameter(1, false);
        return query.getResultList();
    }

    public List<Location> repWithFreePorts() {
        Query query = entityManager.createQuery("Select distinct d.location from Device d,DeviceTypeProperty dtp where d.model.id = dtp.model.id and dtp.property.type = 'PortCount' and cast(dtp.property_value, int)> " +
                        "(select count(dtd.deviceport_from.device) from DeviceToDevice dtd where dtd.deviceport_to.device.id = d.id) ");
        return query.getResultList();
    }

    public List<Location> repWithDevices() {
        Query query = entityManager.createQuery("Select distinct l from Device d inner join d.location as l");
        return query.getResultList();
    }
}